<?php
/**
 * Created by PhpStorm.
 * User: Drunk
 * Date: 2017-3-3
 * Time: 18:08
 */

namespace drunk;

class math{
    private static $_map_bit = [
        1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768,
        65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608,
        16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648,
    ];

    /**
     * 将数字按位元拆分
     * @param int $bits
     * @param int $method {0 : 返回拆分的位元组, 1 : 返回拆分的第一个位元, 2 : 返回拆分的第一个位元下下标}
     * @returns array
     */
    public static function bit_explode($bits, $method = 0) {
        $analysis = [];
        foreach(self::$_map_bit as $k=>$bit) if ($bit & $bits) {
            array_push($analysis, $bit);
            if ($method) return $method == 2 ? $k : $bit;
        }
        return $analysis;
    }

    /**
     * 将位元组合并为位数字
     * @param array $bit_array
     * @returns int
     */
    public static function bit_implode($bit_array) {
        $bits = 0;
        foreach ($bit_array as $k=>$bit) $bits = $bits | $bit;
        return $bits;
    }

    /**
     * 判断是否位元元值
     * @param int $bit
     * @returns bool
     */
    public static function bit_test($bit) {
        return ! ($bit & ($bit - 1));
    }
}